package cn.woo5.test.detector.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping(value = "/detect")
public class DetectController {
  @RequestMapping(value = "/**")
  public String detect(HttpServletRequest request, HttpServletResponse response) throws Exception {
    StringBuilder ret = new StringBuilder();

    Enumeration<String> headerNames = request.getHeaderNames();

    print(ret, "METHOD:\t" + request.getMethod() + "\n\n");

    print(ret, "request uri:\t" + request.getRequestURI() + "\n\n");

    print(ret, "request params:\n");
    Map<String, String[]> params = request.getParameterMap();
    for (Map.Entry<String, String[]> param : params.entrySet()) {
      print(ret, "> " + param.getKey() + ":\t" + Arrays.toString(param.getValue()) + "\n");
    }

    print(ret, "\n\n headers:\n");
    while (headerNames.hasMoreElements()) {
      String headerName = headerNames.nextElement();
      print(ret, "> " + headerName + ":\t" + request.getHeader(headerName) + "\n");
    }

    StringBuilder payload = new StringBuilder();
    BufferedReader reader = request.getReader();
    String line = null;
    while ((line = reader.readLine()) != null) {
      payload.append(line);
    }
    print(ret, "\n\n request payload:" + payload.toString() + "\n\n\n");

    response.setHeader("Content-Type", "text/plain");

    return ret.toString();

  }

  private void print(StringBuilder ret, String string) {
    System.out.println(string);
    ret.append(string);
  }
}
